package cc.wanforme.fsync.task;

import cc.wanforme.fsync.entity.po.TickTask;
import cc.wanforme.fsync.server.ServerCenter;
import cc.wanforme.fsync.server.service.ITickTaskGroupService;
import cc.wanforme.fsync.server.service.ITickTaskService;
import cc.wanforme.fsync.util.LoggerTool;
import jakarta.annotation.PreDestroy;
import org.quartz.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class CronTask {
    private static final Logger log = LoggerTool.getLogger();
    private static final String DEFAULT_GROUP = "DefaultGroup";
//    private StdSchedulerFactory factory ;
    private Scheduler scheduler;

    private ITickTaskService tickTaskService;
    private ITickTaskGroupService taskGroupService;
    private ServerCenter serverCenter;

    private Map<String, JobKey> keys = new HashMap<>();

    public CronTask() throws SchedulerException {
//        factory = new StdSchedulerFactory();
//        scheduler = factory.getScheduler();
//
//        // 启动 schedule
//        scheduler.start();
    }

    @PreDestroy
    public void close() throws SchedulerException {
        scheduler.shutdown();
    }

    /** 程序启动后，设置定时任务 */
    public void setupAllCronTasks() {
        setupCronTasks(tickTaskService.list());
    }

    public void setupCronTasks(List<TickTask> list) {
        if(list == null || list.isEmpty()) {
            return;
        }

        int success = 0;
        for(TickTask task : list) {
            int active = task.getActive()!=null ? task.getActive().intValue() : 0;
            if( active == 1 ) {
                try {
                    setupCronTask(task);
                    success ++;
                } catch (SchedulerException e) {
                    log.error("任务创建失败: " + task.getName() + ","+task.getId(), e);
                }
            }
        }
        log.info("Task-Setup-success: " + success);
    }

    public void setupCronTask(TickTask task) throws SchedulerException {
        log.info("Task-Setup：" + task.getId());
        // 数据
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put(JobWorker.JOB_ID, task.getId());
        jobDataMap.put("taskGroupService", taskGroupService);
        jobDataMap.put("tickTaskService", tickTaskService);
        jobDataMap.put("serverCenter", serverCenter);

        // 具体任务
        JobDetail jobDetail = JobBuilder.newJob(JobWorker.class)
                .usingJobData(jobDataMap)
                .build();

        // 触发器
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity(task.getId()+"", DEFAULT_GROUP)
                .withSchedule(CronScheduleBuilder.cronSchedule(task.getCron()))
                .startNow()
                .build();

        // 交给 schedule 管理
        scheduler.scheduleJob(jobDetail, cronTrigger);
        keys.put(task.getId()+"", jobDetail.getKey()); // 保存 JobKey
    }


    public boolean cancelTask(TickTask task) throws SchedulerException {
        JobKey key = keys.get(task.getId()+"");
        if(key == null) {
            log.info("Task not existed!");
            return false;
        }

        boolean b = scheduler.deleteJob(key);
        log.info("Task-Remove：" + task.getId() + "," + b);
        return b;
    }


    @Autowired
    public void setScheduler(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    @Autowired
    public void setTickTaskService(ITickTaskService tickTaskService) {
        this.tickTaskService = tickTaskService;
    }
    @Autowired
    public void setTaskGroupService(ITickTaskGroupService taskGroupService) {
        this.taskGroupService = taskGroupService;
    }
    @Autowired
    public void setServerCenter(ServerCenter serverCenter) {
        this.serverCenter = serverCenter;
    }
}
